{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Detecting PII with Presidio\n",
    "\n",
    "In this example, we'll show how to detect PII using [Microsoft's Presidio](https://colab.research.google.com/corgiredirector?site=https%3A%2F%2Fmicrosoft.github.io%2Fpresidio%2F) and Langkit\n",
    "\n",
    "Note: The `regexes` module also provides basic PII detection capabilities. The difference is that `regexes` uses a simple list of regex patterns, while `pii` (the module in this example) uses much more sophisticated models and patterns to detect PII, at the expense of requiring more resources to do so.\n",
    "\n",
    "## Setup\n",
    "\n",
    "The `pii` module is included when installing the `all` extra, so let's install it. This module will use `presidio` as a dependency, which itself requires `spacy`. Extra models will need to be automatically installed, such as Spacy's `en_core_web_lg`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install langkit[all]==0.0.29"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Extracting PIIs from Prompts and Responses\n",
    "\n",
    "To extract PII entities from your prompt and responses, you simply need to import the module and use it with langkit's `extract`. Let's define some examples to test it out.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "prompts = [\n",
    "    \"Hello, my name is David Johnson and I live in Maine. \\\n",
    "    My credit card number is 4095-2609-9393-4932 and my crypto wallet id is 16Yeky6GMjeNkAiNcBY7ZhrLoMSgg1BoyZ.\",\n",
    "    \"On September 18 I visited microsoft.com and sent an email to test@presidio.site,  from the IP 192.168.0.1.\",\n",
    "    \"My passport: 191280342 and my phone number: (212) 555-1234.\",\n",
    "    \"This is a valid International Bank Account Number: IL150120690000003111111 . \\\n",
    "    Can you please check the status on bank account 954567876544?\",\n",
    "    \"Kate's social security number is 078-05-1126.  Her driver license? it is 1234567A.\",\n",
    "    \"Hi, My name is John.\",\n",
    "]\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can use `extract` by passing a single prompt and/or response in a dictionary, like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'prompt': 'Hello, my name is David Johnson and I live in Maine.     My credit card number is 4095-2609-9393-4932 and my crypto wallet id is 16Yeky6GMjeNkAiNcBY7ZhrLoMSgg1BoyZ.',\n",
       " 'response': 'Hi, My name is John.',\n",
       " 'prompt.pii_presidio.result': '[{\"type\": \"CREDIT_CARD\", \"start\": \"82\", \"end\": \"101\", \"score\": \"1.0\"}, {\"type\": \"CRYPTO\", \"start\": \"129\", \"end\": \"163\", \"score\": \"1.0\"}]',\n",
       " 'prompt.pii_presidio.entities_count': 2,\n",
       " 'response.pii_presidio.result': '[]',\n",
       " 'response.pii_presidio.entities_count': 0}"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langkit import extract, pii\n",
    "\n",
    "data = {\"prompt\": prompts[0],\n",
    "        \"response\": prompts[-1]}\n",
    "result = extract(data)\n",
    "\n",
    "result"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The list of searched entities is defined in the `PII_entities.json` under the Langkit folder. You can also pass your own list of entities when initializing the `PII` module.\n",
    "\n",
    "Let's write a file called `my_custom_entities.json` and then use it to initialize the `PII` module."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Overwriting my_custom_entities.json\n"
     ]
    }
   ],
   "source": [
    "%%writefile my_custom_entities.json\n",
    "\n",
    "{\n",
    "  \"entities\": [\"CREDIT_CARD\"]\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'prompt': 'Hello, my name is David Johnson and I live in Maine.     My credit card number is 4095-2609-9393-4932 and my crypto wallet id is 16Yeky6GMjeNkAiNcBY7ZhrLoMSgg1BoyZ.',\n",
       " 'response': 'Hi, My name is John.',\n",
       " 'prompt.pii_presidio.result': '[{\"type\": \"CREDIT_CARD\", \"start\": \"82\", \"end\": \"101\", \"score\": \"1.0\"}]',\n",
       " 'prompt.pii_presidio.entities_count': 1,\n",
       " 'response.pii_presidio.result': '[]',\n",
       " 'response.pii_presidio.entities_count': 0}"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pii.init(entities_file_path=\"my_custom_entities.json\")\n",
    "data = {\"prompt\": prompts[0],\n",
    "        \"response\": prompts[-1]}\n",
    "result = extract(data)\n",
    "\n",
    "result"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that, in the cell above, only the `CREDIT_CARD` entity is detected, since it is the only one defined in `my_custom_entities.json`.\n",
    "\n",
    "### Supported Entities\n",
    "\n",
    "You can check the list of supported entities in Presidio's documentation [here](https://microsoft.github.io/presidio/supported_entities/)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Extracting PII from a Pandas Dataframe\n",
    "\n",
    "You can also use the `pii` module to extract PII from a Pandas Dataframe. The `pii.extract` function takes a Pandas Dataframe as input and returns a new Dataframe with the extracted PII."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>prompt</th>\n",
       "      <th>response</th>\n",
       "      <th>prompt.pii_presidio.result</th>\n",
       "      <th>prompt.pii_presidio.entities_count</th>\n",
       "      <th>response.pii_presidio.result</th>\n",
       "      <th>response.pii_presidio.entities_count</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Hello, my name is David Johnson and I live in ...</td>\n",
       "      <td>Hello, my name is David Johnson and I live in ...</td>\n",
       "      <td>[{\"type\": \"CREDIT_CARD\", \"start\": \"82\", \"end\":...</td>\n",
       "      <td>2</td>\n",
       "      <td>[{\"type\": \"CREDIT_CARD\", \"start\": \"82\", \"end\":...</td>\n",
       "      <td>2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>On September 18 I visited microsoft.com and se...</td>\n",
       "      <td>On September 18 I visited microsoft.com and se...</td>\n",
       "      <td>[{\"type\": \"IP_ADDRESS\", \"start\": \"94\", \"end\": ...</td>\n",
       "      <td>3</td>\n",
       "      <td>[{\"type\": \"IP_ADDRESS\", \"start\": \"94\", \"end\": ...</td>\n",
       "      <td>3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>My passport: 191280342 and my phone number: (2...</td>\n",
       "      <td>My passport: 191280342 and my phone number: (2...</td>\n",
       "      <td>[{\"type\": \"PHONE_NUMBER\", \"start\": \"44\", \"end\"...</td>\n",
       "      <td>5</td>\n",
       "      <td>[{\"type\": \"PHONE_NUMBER\", \"start\": \"44\", \"end\"...</td>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>This is a valid International Bank Account Num...</td>\n",
       "      <td>This is a valid International Bank Account Num...</td>\n",
       "      <td>[{\"type\": \"IBAN_CODE\", \"start\": \"51\", \"end\": \"...</td>\n",
       "      <td>3</td>\n",
       "      <td>[{\"type\": \"IBAN_CODE\", \"start\": \"51\", \"end\": \"...</td>\n",
       "      <td>3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>Kate's social security number is 078-05-1126. ...</td>\n",
       "      <td>Kate's social security number is 078-05-1126. ...</td>\n",
       "      <td>[{\"type\": \"US_SSN\", \"start\": \"33\", \"end\": \"44\"...</td>\n",
       "      <td>3</td>\n",
       "      <td>[{\"type\": \"US_SSN\", \"start\": \"33\", \"end\": \"44\"...</td>\n",
       "      <td>3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>Hi, My name is John.</td>\n",
       "      <td>Hi, My name is John.</td>\n",
       "      <td>[]</td>\n",
       "      <td>0</td>\n",
       "      <td>[]</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                                              prompt  \\\n",
       "0  Hello, my name is David Johnson and I live in ...   \n",
       "1  On September 18 I visited microsoft.com and se...   \n",
       "2  My passport: 191280342 and my phone number: (2...   \n",
       "3  This is a valid International Bank Account Num...   \n",
       "4  Kate's social security number is 078-05-1126. ...   \n",
       "5                               Hi, My name is John.   \n",
       "\n",
       "                                            response  \\\n",
       "0  Hello, my name is David Johnson and I live in ...   \n",
       "1  On September 18 I visited microsoft.com and se...   \n",
       "2  My passport: 191280342 and my phone number: (2...   \n",
       "3  This is a valid International Bank Account Num...   \n",
       "4  Kate's social security number is 078-05-1126. ...   \n",
       "5                               Hi, My name is John.   \n",
       "\n",
       "                          prompt.pii_presidio.result  \\\n",
       "0  [{\"type\": \"CREDIT_CARD\", \"start\": \"82\", \"end\":...   \n",
       "1  [{\"type\": \"IP_ADDRESS\", \"start\": \"94\", \"end\": ...   \n",
       "2  [{\"type\": \"PHONE_NUMBER\", \"start\": \"44\", \"end\"...   \n",
       "3  [{\"type\": \"IBAN_CODE\", \"start\": \"51\", \"end\": \"...   \n",
       "4  [{\"type\": \"US_SSN\", \"start\": \"33\", \"end\": \"44\"...   \n",
       "5                                                 []   \n",
       "\n",
       "   prompt.pii_presidio.entities_count  \\\n",
       "0                                   2   \n",
       "1                                   3   \n",
       "2                                   5   \n",
       "3                                   3   \n",
       "4                                   3   \n",
       "5                                   0   \n",
       "\n",
       "                        response.pii_presidio.result  \\\n",
       "0  [{\"type\": \"CREDIT_CARD\", \"start\": \"82\", \"end\":...   \n",
       "1  [{\"type\": \"IP_ADDRESS\", \"start\": \"94\", \"end\": ...   \n",
       "2  [{\"type\": \"PHONE_NUMBER\", \"start\": \"44\", \"end\"...   \n",
       "3  [{\"type\": \"IBAN_CODE\", \"start\": \"51\", \"end\": \"...   \n",
       "4  [{\"type\": \"US_SSN\", \"start\": \"33\", \"end\": \"44\"...   \n",
       "5                                                 []   \n",
       "\n",
       "   response.pii_presidio.entities_count  \n",
       "0                                     2  \n",
       "1                                     3  \n",
       "2                                     5  \n",
       "3                                     3  \n",
       "4                                     3  \n",
       "5                                     0  "
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "\n",
    "pii.init()\n",
    "data = pd.DataFrame({\"prompt\": prompts, \"response\": prompts})\n",
    "\n",
    "result = extract(data)\n",
    "\n",
    "result"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results Format\n",
    "For each column (prompt or response), `pii` will generate two additional columns:\n",
    "\n",
    "__`pii_presidio.result`__\n",
    "\n",
    "This is a list of dictionaries, where each dictionary represents a single detected entity. In it, we have the following keys:\n",
    "\n",
    "- type: the type of entity detected\n",
    "- start: the start index of the entity in the text\n",
    "- end: the end index of the entity in the text\n",
    "- score: the confidence score of the entity\n",
    "\n",
    "The result is provided as json formatted string.\n",
    "\n",
    "__`pii_presidio.entities_count`__\n",
    "\n",
    "Contains the total number of entities detected in the text. It's equal to the length of the list in `pii_presidio.result`.\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "langkit-rNdo63Yk-py3.8",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
